package sy.action;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import sy.annotation.MethodName;
import sy.bo.JsonResult;
import sy.bo.SessionInfo;
import sy.po.User;
import sy.service.ResourceService;
import sy.service.UserService;
import sy.util.QueryFilter;

/**
 * 
 * @author 孙宇
 *
 */
@IocBean(name = "loginAction")
public class LoginAction {

	// 注入userService
	@Inject("refer:userService")
	private UserService userService;

	// 注入resourceService
	@Inject("refer:resourceService")
	private ResourceService resourceService;

	/**
	 * 登录，以/global/开头的方法是不会进行session验证的
	 * 
	 * @Aop({ "actionLogInterceptor" })的作用是记录操作日志
	 * 
	 * @param session
	 * @return
	 */
	@At("/global/login")
	@Aop({ "actionLogInterceptor" })
	@MethodName(name = "登录")
	public JsonResult login(HttpSession session, @Param("::user.") User user) {
		JsonResult result = new JsonResult();

		if (user.getName() == null || user.getPwd() == null) {
			result.setInfo("登录失败！用户名或密码不能为空！");
		} else {
			QueryFilter q = new QueryFilter();
			q.addFilter("Q_name_=", user.getName());
			q.addFilter("Q_pwd_=", DigestUtils.sha1Hex(user.getPwd()));
			q.addFilter("Q_companyId_=", user.getCompanyId());

			User u = userService.fetchLinks(q.getCondition());
			if (u != null) {
				session.setAttribute(SessionInfo.SESSIONINFONAME, new SessionInfo(u, resourceService.getResourceListByUser(u)));// 如果找到了用户，说明登陆成功，将用户信息保存到session中，便于以后使用
				result.setSuccess(true);
				result.setResult(u);
				result.setInfo("登录成功！");
			} else {
				result.setInfo("登录失败！用户名或密码或公司错误！");
			}
		}

		return result;
	}

	/**
	 * 退出登录，销毁session
	 * 
	 * @param session
	 */
	@At("/logout")
	@Ok("redirect:/")
	@Aop({ "actionLogInterceptor" })
	@MethodName(name = "注销")
	public void logout(HttpSession session) {
		if (session != null) {
			session.invalidate();
		}
	}

}
